﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using HZ.Supervise.Model.Enum;

namespace HZ.Supervise.Web.Message
{
    public partial class WarningSetupForHospital : BasePage
    {
        public WarningSetupForHospital()
        {
            this.ModuleNo = Module.预警设置.ToString();
            this.PageOperateType = OperateType.数量金额预警.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindSort();
                BindList();
            }         
        }

        /// <summary>
        /// 绑定药品类别
        /// </summary>
        private void BindSort()
        {          
            HZ.Supervise.BLL.BLL_Sort bllSort = new HZ.Supervise.BLL.BLL_Sort();  
            DataTable dtSort = bllSort.GetSort();
            ddlDrugSort.DataSource = dtSort;
            ddlDrugSort.DataTextField = "SortName";
            ddlDrugSort.DataValueField = "SortID";
            ddlDrugSort.DataBind();

            ddlDrugSort.Items.Insert(0, "---请选择---");
        }
                 

        /// <summary>
        /// 制定消息
        /// 张雄 modify 2011.4.21
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirmMessage_Click(object sender, EventArgs e)
        {
            //将数据存入数据库
            Model.MessageTypeDetail message = new HZ.Supervise.Model.MessageTypeDetail();

            message.AddTime = DateTime.Now;//添加时间
            if (HZ.Fun.CheckString(hfdRecivedArea.Value.Trim()) != "")
            {
                message.AreaId = HZ.Fun.CheckString(hfdRecivedArea.Value.Trim().TrimEnd(','));//地区编号
                message.AreaName = HZ.Fun.CheckString(hfdRecivedAreaName.Value.Trim().TrimEnd(','));//地区名称
            }
            else
            {
                //HZ.Web.WebUtil.Alert("请选择一个地区",this);
                //return;
                message.AreaId = "";
                message.AreaName = "所有地区";
            }
            if (HZ.Fun.CheckString(hdfRecivedHospital.Value.Trim()) != "")
            {
                message.HospitalId = HZ.Fun.CheckString(hdfRecivedHospital.Value.Trim().TrimEnd(','));//医院编号
                message.HospitalName = HZ.Fun.CheckString(hdfRecivedHospitalName.Value.Trim().TrimEnd(','));//医院名称
            }
            else
            {
                //HZ.Web.WebUtil.Alert("请选择一个医院", this);
                //return;
                message.HospitalId = "";
                message.HospitalName = "所有医院";
            }
            if (HZ.Fun.CheckString(ddlDrugSort.SelectedValue) != "---请选择---")
            {
                message.SortId = HZ.Fun.CheckString(ddlDrugSort.SelectedValue.Trim());//药品分类编号
                message.SortName = HZ.Fun.CheckString(ddlDrugSort.SelectedItem.Text.Trim());//分类名称
            }
            else
            {
                message.SortId = "";
                message.SortName = "所有类别";
            }
            if (HZ.Fun.CheckString(hdfRecivedGoods.Value) != "")
            {
                message.ProductName = HZ.Fun.CheckString(hdfRecivedGoodsName.Value.Trim().TrimEnd(','));//药品名称
                message.GoodsID = HZ.Fun.CheckString(hdfRecivedGoods.Value.Trim().TrimEnd(','));//药品编号
            }
            //else 
            //{
            //    message.ProductName = "所有药物";
            //}
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "")
            {
                message.ProductName = "所有药物";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "0")
            {
                message.ProductName = "日常采购";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "1")
            {
                message.ProductName = "临时采购";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "2")
            {
                message.ProductName = "应急采购";
            }


            //if (ddlSortSource.SelectedValue != "")
            //{
            //    message.SortSource = HZ.Fun.CheckString(ddlSortSource.SelectedValue.Trim());
            //}
            //else
            //{
            //    HZ.Web.WebUtil.Alert("请选择采购类型！", this);
            //    return;
            //}
            if (HZ.Fun.CheckString(this.txtTimeOfRange.Text) == "")
            {
                HZ.Web.WebUtil.Alert("请选择触发条件！", this);
            }

            message.TypeId = 1;//规则编号
            message.TypeKey = "";
            message.TypeName = "医院药品监控";//规则名称
            message.UserId = CurrentAccount.UserID;//用户编号
            message.Level = ddlLevel.SelectedItem.Text;//预警级别
            message.Is_Work = false;
            message.MessageDetailId = Guid.NewGuid().ToString();//主键


            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
                message.Days = int.Parse(HZ.Fun.CheckString(txtTimeOfRange.Text.Trim()));//预警范围
            }
            message.DayType = ddlTime.SelectedItem.Text;//时间类型
            if (!string.IsNullOrEmpty(txtAmount.Text.Trim()))
            {
                message.AmountLeft = Convert.ToDecimal(HZ.Fun.CheckString(txtAmount.Text.Trim()));//预警金额范围左边文本框数据
                message.AmountParentLeft = int.Parse(ddlAmountCompare.SelectedValue.ToString());
            }
            if (!string.IsNullOrEmpty(txtAmount2.Text.Trim()))
            {
                message.AmountRight = Convert.ToDecimal(HZ.Fun.CheckString(txtAmount2.Text.Trim()));//预警金额范围右边文本框数据
                message.AmountParentRight = int.Parse(ddlAmountCompare2.SelectedValue.ToString());
            }

            if (!string.IsNullOrEmpty(txtCount.Text.Trim()))
            {
                message.CountLeft = Int64.Parse(HZ.Fun.CheckString(txtCount.Text.Trim()));//预警数量范围左边文本框数据
                message.CountParentLeft = int.Parse(ddlCountCompare.SelectedValue.ToString());
            }

            if (!string.IsNullOrEmpty(txtCount2.Text.Trim()))
            {
                message.CountRight = Int64.Parse(HZ.Fun.CheckString(txtCount2.Text.Trim()));//预警数量右边文本框数据
                message.CountParentRight = int.Parse(ddlCountCompare2.SelectedValue.ToString());
            }

            message.ConnectType = int.Parse(ddlConnectType.SelectedValue.ToString());
            message.SqlStringWhere = MakeSqlStringWhere(message.AddTime);
            message.SqlStringHaving = MakeSqlStringHaving();
            message.SqlDescription = MakeSqlDescription();
            message.Is_Del = false;//未删除


            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            if (ibllMessage.IsExistMessageTypeDetail(message))
            {
                HZ.Web.WebUtil.Alert("规则重复",this);
                return;
            }
            try
            {
                int i = ibllMessage.InsertIntoMessageTypeDetail(message);

                if (i == 0)
                {
					HZ.Web.WebUtil.Alert("添加失败",this.Page);
                }
                else
                {
                    HZ.Web.WebUtil.Alert("添加成功",this.Page);

                    BindList();
                    //清空
                    txtAmount.Text = "";
                    txtAmount2.Text = "";
                    txtArea.Text = "";
                    txtCount.Text = "";
                    txtCount2.Text = "";
                    txtGoods.Text = "";
                    txtHospital.Text = "";
                    txtTimeOfRange.Text = "";
                    hdfRecivedGoods.Value = "";
                    hdfRecivedHospital.Value = "";
                    hfdRecivedArea.Value = "";
                    hfdRecivedAreaName.Value = "";
                    ddlDrugSort.SelectedValue = "---请选择---";
                    ddlSortSource.SelectedValue = "";
                    ddlConnectType.SelectedValue = "0";
                    ddlLevel.SelectedValue = "0";
                    ddlTime.SelectedValue = "0";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 生成Having语句
        /// </summary>
        /// <returns></returns>
        protected string MakeSqlStringHaving()
        {
            StringBuilder sb = new StringBuilder("",255);
            if (!string.IsNullOrEmpty(txtCount.Text.Trim()) && !string.IsNullOrEmpty(txtCount2.Text.Trim()))
            {
                double count1 = double.Parse(HZ.Fun.CheckString(txtCount.Text.Trim()));
                double count2 = double.Parse(HZ.Fun.CheckString(txtCount2.Text.Trim()));
                if (count1 < count2)
                {
                    sb.AppendFormat(" (SUM(PurchaseCount)>={0} AND SUM(PurchaseCount)<={1})", count1, count2);
                }
                else if (count1 > count2)
                {
                    sb.AppendFormat(" (SUM(PurchaseCount)>={0} OR SUM(PurchaseCount)<={1})", count1, count2);
                }
            }
            else if (!string.IsNullOrEmpty(txtCount.Text.Trim()))
            {
                sb.AppendFormat(" SUM(PurchaseCount)>={0}", txtCount.Text.Trim());
            }
            else if (!string.IsNullOrEmpty(txtCount2.Text.Trim()))
            {
                sb.AppendFormat(" SUM(PurchaseCount)<={0}", txtCount2.Text.Trim());
            }

            if ((!string.IsNullOrEmpty(txtCount.Text.Trim()) || !string.IsNullOrEmpty(txtCount2.Text.Trim())) && (!string.IsNullOrEmpty(txtAmount.Text.Trim()) || !string.IsNullOrEmpty(txtAmount2.Text.Trim())))
            {
                if (!string.IsNullOrEmpty(ddlConnectType.SelectedItem.Text))
                {
                    sb.AppendFormat(" {0}", ddlConnectType.SelectedItem.Text == "两者都满足" ? " AND " : " OR ");
                }
            }
            if (!string.IsNullOrEmpty(txtAmount.Text.Trim()) && !string.IsNullOrEmpty(txtAmount2.Text.Trim()))
            {
                double amount1 = double.Parse(HZ.Fun.CheckString(txtAmount.Text.Trim()));
                double amount2 = double.Parse(HZ.Fun.CheckString(txtAmount2.Text.Trim()));
                if (amount1 < amount2)
                {
                    sb.AppendFormat(" (SUM(Amount)>={0} AND SUM(Amount)<={1})", amount1, amount2);
                }
                else if (amount1 > amount2)
                {
                    sb.AppendFormat(" (SUM(Amount)>={0} OR SUM(Amount)<={1})", amount1, amount2);
                }
            }
            else if (!string.IsNullOrEmpty(txtAmount.Text.Trim()))
            {
                sb.AppendFormat(" SUM(Amount)>={0}", txtAmount.Text.Trim());
            }
            else if (!string.IsNullOrEmpty(txtAmount2.Text.Trim()))
            {
                sb.AppendFormat(" SUM(Amount)<={0}", txtAmount2.Text.Trim());
            }
            return sb.ToString();
        }
        /// <summary>
        /// 生成Where语句
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        protected string MakeSqlStringWhere(DateTime time)
        {
            StringBuilder sb = new StringBuilder("",255);

            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
                switch (ddlTime.SelectedItem.Text)
                    {
                    case "日":
                            string timeday = string.Format("DATEADD({0},{1}, '{2}')", "day", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ExecuteTime>'{1}' and ExecuteTime<{0}", timeday, time);
                            break;
                    case "周":
                            string timeweek = string.Format("DATEADD({0},{1}, '{2}')", "week", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ExecuteTime>'{1}' and ExecuteTime<{0}", timeweek, time);
                            break;
                    case "月":
                            string timemonth = string.Format("DATEADD({0},{1}, '{2}')", "month", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ExecuteTime>'{1}' and ExecuteTime<{0}", timemonth, time);
                            break;
                    }
            }
            if (ddlSortSource.SelectedValue.ToString() != "")
            {
                sb.AppendFormat(" AND SortSource='{0}' ", ddlSortSource.SelectedValue.ToString());
            }

            #region 地区医院
            if (hdfRecivedHospital.Value.Trim() != "")
            {
                sb.AppendFormat(" AND HospitalId IN({0}) ", MakeQueryIn(hdfRecivedHospital.Value.Trim().TrimEnd(',')));
            }
            else
            {
                if (hfdRecivedArea.Value.Trim() != "")
                {
                    sb.AppendFormat(" AND AreaId IN({0}) ", MakeQueryIn(hfdRecivedArea.Value.Trim().TrimEnd(',')));
                }
            }
            #endregion
            #region 药品
            if (hdfRecivedGoods.Value.Trim() != "")
            {
                sb.AppendFormat(" AND GoodsId IN({0}) ", MakeQueryIn(hdfRecivedGoods.Value.Trim().TrimEnd(',')));
            }
            else
            {
                if (ddlDrugSort.SelectedValue.ToString() != "---请选择---")
                {
                    sb.AppendFormat(" AND SortId='{0}' ", ddlDrugSort.SelectedValue.ToString());
                }
            }
            #endregion
            return sb.ToString();
        }

        /// <summary>
        /// 生成Sql描述语句
        /// </summary>
        /// <returns></returns>
        protected string MakeSqlDescription()
        {
            StringBuilder sb = new StringBuilder("", 255);
            if (!string.IsNullOrEmpty(txtCount.Text.Trim()) && !string.IsNullOrEmpty(txtCount2.Text.Trim()))
            {
                sb.AppendFormat("预警数量大于等于<font color='RED'>{0}</font>小于等于<font color='GREEN'>{1}</font>", txtCount.Text.Trim(), txtCount2.Text.Trim());
            }
            else if (!string.IsNullOrEmpty(txtCount.Text.Trim()))
            {
                sb.AppendFormat("预警数量大于等于<font color='RED'>{0}</font>", txtCount.Text.Trim());
            }
            else if (!string.IsNullOrEmpty(txtCount2.Text.Trim()))
            {
                sb.AppendFormat("预警数量小于等于<font color='RED'>{0}</font>", txtCount2.Text.Trim());
            }
            if ((!string.IsNullOrEmpty(txtCount.Text.Trim()) || !string.IsNullOrEmpty(txtCount2.Text.Trim())) && (!string.IsNullOrEmpty(txtAmount.Text.Trim()) || !string.IsNullOrEmpty(txtAmount2.Text.Trim())))
            {
                if (!string.IsNullOrEmpty(ddlConnectType.SelectedItem.Text))
                {
                    sb.AppendFormat("{0}", ddlConnectType.SelectedItem.Text == "两者都满足" ? "同时" : "或者");
                }
            }
            if (!string.IsNullOrEmpty(txtAmount.Text.Trim()) && !string.IsNullOrEmpty(txtAmount2.Text.Trim()))
            {
                sb.AppendFormat("预警金额大于等于<font color='RED'>{0}</font>小于等于<font color='GREEN'>{1}</font>", txtAmount.Text.Trim(), txtAmount2.Text.Trim());
            }
            else if (!string.IsNullOrEmpty(txtAmount.Text.Trim()))
            {
                sb.AppendFormat("预警金额大于等于<font color='RED'>{0}</font>", txtAmount.Text.Trim());
            }
            else if (!string.IsNullOrEmpty(txtAmount2.Text.Trim()))
            {
                sb.AppendFormat("预警金额小于等于<font color='RED'>{0}</font>", txtAmount2.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
                sb.AppendFormat("同时预警范围为<font color='RED'>{0}</font>{1}", int.Parse(HZ.Fun.CheckString(txtTimeOfRange.Text.Trim())), ddlTime.SelectedItem.Text);
            }
            return sb.ToString();
        }

        protected string MakeQueryIn(string msg)
        {
            StringBuilder sb = new StringBuilder();
            string[] arr = msg.Trim().Split(',');
            for (int i = 0; i < arr.Length; i++)
            {
                if (i == 0)
                {
                    sb.AppendFormat("'{0}'", arr[i]);
                }
                else
                {
                    sb.AppendFormat(",'{0}'", arr[i]);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        public void BindList()
        {
            int t = 0;  
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            Model.MessageTypeDetail messageTypeDetail = new HZ.Supervise.Model.MessageTypeDetail();
            messageTypeDetail.UserId = CurrentAccount.UserID;
            messageTypeDetail.Is_Work = false;
            messageTypeDetail.Is_Del = false;

            DataTable dt = new DataTable();
            dt = ibllMessage.GetMessageTypeDetailByType(messageTypeDetail,"1", AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);

            //HZ.Supervise.Web.Function.AddColumn(dt,"SortSource");
            gvwWarningStart.DataSource = dt;
            this.AspNetPager1.RecordCount = t;
            gvwWarningStart.DataBind();
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList();
        }
        /// <summary>
        /// 行数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwWarningStart_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            for (int i = 0; i < gvwWarningStart.Rows.Count; i++)
            {
                string areaName = ((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text.ToString();
                ((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text = SubStr(areaName, 12);

                string hospitalName = ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblHospitalName"))).Text.ToString();
                if (hospitalName != "")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblHospitalName"))).Text = SubStr(hospitalName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblHospitalName"))).Text = "所有医院";
                }

                string productName = ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text.ToString();
                if (productName != "")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text = SubStr(productName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text = "所有药品";
                }
                string SortName = ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text.ToString();
                if (SortName != "---请选择---")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text = SubStr(SortName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text = "所有分类";
                }
             
            }
        }
        /// <summary>
        /// 字符串截取
        /// </summary>
        /// <param name="sString"></param>
        /// <param name="nLeng"></param>
        /// <returns></returns>
        string SubStr(string sString, int nLeng)
        {
            if (sString.Length <= nLeng)
            {
                return sString;
            }
            string sNewStr = sString.Substring(0, nLeng);
            sNewStr = sNewStr + "...";
            return sNewStr;
        }
        /// <summary>
        /// 删除预警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelte_Click(object sender, EventArgs e)
        {
            string chkedids = Request.Form["chk"];
            int flag = 1;
            if (string.IsNullOrEmpty(chkedids))
            {
                HZ.Web.WebUtil.Alert("请选择一个规则！",this);
                return;
            }
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            foreach (var item in chkedids.Split(','))
            {
                flag = ibllMessage.DeleteMessageTypeDetail(item);
            }
            if (flag == 1)
            {
                HZ.Web.WebUtil.Alert("删除成功！",this);
            }
            else
            {
                HZ.Web.WebUtil.Alert("删除失败！",this);
            }
            BindList();
        }
        /// <summary>
        /// 启用预警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnStart_Click(object sender, EventArgs e)
        {
            string chkedids = Request.Form["chk"];
            int flag = 1;
            if (string.IsNullOrEmpty(chkedids))
            {
                HZ.Web.WebUtil.Alert("请选择一个规则！",this);
                return;
            }
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            foreach (var item in chkedids.Split(','))
            {
                flag = ibllMessage.WarningSwitch(item, "1");
            }
            if (flag == 1)
            {
                HZ.Web.WebUtil.Alert("启用成功！",this);
            }
            else
            {
                HZ.Web.WebUtil.Alert("启用失败！",this);
            }
            BindList();
        }

        protected void HzButton1_Click(object sender, EventArgs e)
        {
            BLL.BLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            ibllMessage.InsertIntoMessageSend();
        }     
       
    }
}
